English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
C ++ map operador[]função é usada para usar a chaveChaveacessar elementos do map.
É semelhante aat()função. A única diferença entre elas é que, se a chave acessada não existir no map, é lançada uma exceção; por outro lado, se a chave não existir no map,operador[]Insira a chave no map.
Considere a chavek,a sintaxe é:
mapped_type& operador[] (const key_type& k); // do C++ 11 antes mapped_type& operador[] (const key_type& k); //do C++ 11 Começando mapped_type& operador[] (key_type&& k); //do C++ 11 Começando
k:chave de acesso ao elemento do map.
Ele usa chaves para retornar uma referência ao valor do elemento map.
Vamos ver um exemplo simples de acesso a elementos.
#include <iostream> #include <map> using namespace std; int main() { map<char, int> m = { {'a', 1}, {'b', 2}, {'c', 3}, {'d', 4}, {'e', 5}, }; cout << "O Map contém os seguintes elementos" << endl; cout << "m['a'] = " << m['a'] << endl; cout << "m['b'] = " << m['b'] << endl; cout << "m['c'] = " << m['c'] << endl; cout << "m['d'] = " << m['d'] << endl; cout << "m['e'] = " << m['e'] << endl; return 0; }
Saída:
O Map contém os seguintes elementos m['a'] = 1 m['b'] = 2 m['c'] = 3 m['d'] = 4 m['e'] = 5
Aqui, a função []operador é usada para acessar os elementos do map.
Vamos ver um exemplo simples, usando suas chaves para adicionar elementos.
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,string> mymap = { { 101,"" }, { 102,"" }, { 103,""} }; mymap[101]="w3codebox"; mymap[102]="."; mymap[103]="com"; //Print the value associated with the key101The associated value, i.e., w}}3codebox cout << mymap[101]; // Print the value associated with the key102The associated value, i.e., . cout << mymap[102]; //Print the value associated with the key103The associated value, i.e., com cout << mymap[103]; return 0; }
Saída:
oldtoolbag.com
In the above example, operator [] is used to add elements associated with keys after initialization.
Let's look at a simple example to change the value associated with the key.
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<int,string> mymap = { { 100, "Nikita"}, { 200, "Deep" }, { 300, "Priya" }, { 400, "Suman" }, { 500, "Aman" }}; cout << "The element is:" << endl; for (auto& x: mymap) { cout << x.first << ": " << x.second << '\n'; } mymap[100] = "Nidhi"; //The value associated with the key100 associated value changed to Nidhi mymap[300] = "Pinku"; //The value associated with the key300 associated value changed to Pinku mymap[500] = "Arohi"; //The value associated with the key500 associated value changed to Arohi cout << "\nThe changed element is:" << endl; for (auto& x: mymap) { cout << x.first << ": " << x.second << '\n'; } return 0; }
Saída:
The element is: 100: Nikita 200: Deep 300: Priya 400: Suman 500: Aman The changed element is: 100: Nidhi 200: Deep 300: Pinku 400: Suman 500: Arohi
In the above example, the operator [] function is used to change the value associated with its key.
Let's look at a simple example to distinguish operator [] and at().
#include <iostream> #include <string> #include <map> using namespace std; int main () { map<char,string> mp = { { 'a',"Java"}, { 'b', "C"++"}, { 'c', "Python" }; cout << endl << mp['a']; cout << endl << mp['b']; cout << endl << mp['c']; mp['d'] = "SQL"; cout << endl << mp['d']; try { mp.at('z'); //Since there is no key with value 'z' in the map, an exception will be thrown catch(const out_of_range &e) { cout << endl << "\nExceção de Escopo Fora do Intervalo " << e.what(); } return 0; }
Saída:
Java C++ Python SQL Exceção de Escopo Fora do Intervalo map::at
No exemplo acima, quando usamos a função at(), ela lança a exceção out_of_range, porque não há valor para a chave z no mapeamento, e quando usamos operator [] para adicionar elementos na chave valor d, porque não há chave no map com valor 'd', ele inserirá um par de chave valor com chave 'd' e valor 'SQL'.